<template>
  <div>
    <h1>我的购物车</h1>
    <el-card style="width: 1200px;" class="block">
      <el-tabs v-model="activeName">
        <!-- 购物车商品 -->
        <el-tab-pane label="全部商品" name="first">

          <el-table
            :data="addedGoods"
            @select="handleSum"
            @select-all="handleSum"

            ref="multipleTable">

            <!-- 复选框 -->
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="name" label="名称" width="180"></el-table-column>

            <el-table-column prop="img" label="商品" width="150">

              <template slot-scope="scope">
                <a v-on:click="goodsMsg(scope.$index)">
                  <img :src="scope.row.img" width="100" height="100">
                </a>
              </template>
            </el-table-column>

            <el-table-column label="数量" prop="count" width="250">
              <!-- 使用计数器来添加数量，绑定表格数据行对应的count -->
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.count" @change="handleSum(scope.row.count,scope.row.name)"
                                 :min="1"></el-input-number>
              </template>
            </el-table-column>

            <el-table-column prop="price" label="单价" width="150">
              <template slot-scope="prices">
                <span>￥{{prices.row.price}}</span>
              </template>
            </el-table-column>

            <el-table-column label="金额" prop="money1" width="150">
              <template slot-scope="money">
                <span>￥{{money.row.price*money.row.count}}</span>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="handleDelete(scope.$index,scope.row.name)">删除</el-button>
                <el-button size="mini" type="danger" @click="pay(scope.row.name,scope.row.price,scope.row.count)">点击支付
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div style="margin: 20px;">
            <div style="float: left">
              已选数量：<span style="color:#000;margin-right:  50px">{{num}}</span>
              总价：<span style="color: red; ">￥{{sum}}</span>
            </div>
            <div style="float: right">
              <el-button type="text" size="mini" @click="payAll(sum)" style="font-size: 20px;margin-left: 50px">点击支付
              </el-button>
            </div>
          </div>


        </el-tab-pane>
        <!-- 添加商品 -->
        <!-- <el-tab-pane label="添加商品" name="second">
           <el-table :data="goods">
             <el-table-column prop="name" label="名称"></el-table-column>
             <el-table-column prop="price" label="单价"></el-table-column>
             <el-table-column label="操作">
               <template slot-scope="scope">
                 <el-button size="mini" type="primary" @click="handleAdd(scope.$index)">添加</el-button>
               </template>
             </el-table-column>
           </el-table>
         </el-tab-pane>-->
      </el-tabs>
    </el-card>
    <div>
      <el-pagination align='center'
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-sizes="[1,5,10,20]"
                     :page-size="pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="addedGoods.length">
      </el-pagination>
    </div>


  </div>
</template>

<script>
  export default {
    name: "Cart",
    data() {
      return {
        sum: 0,
        num: 0,
        count1: 0,
        activeName: 'first',
        // 添加进购物车的商品数组
        addedGoods: [],
        goods: [],
        currentPage: 1, // 当前页码
        total: 20, // 总条数
        pageSize: 4,// 每页的数据条数
        // 设置的商品
        /* goods: [{
           name: '手机',
           price: 1000,
           count: 1
         }, {
           name: '电脑',
           price: 2000,
           count: 1
         }, {
           name: '平板',
           price: 3000,
           count: 1
         }, {
           name: '电视',
           price: 4000,
           count: 1
         }, {
           name: '空调',
           price: 5000,
           count: 1
         }]*/
      }
    },
    methods: {
      //每页条数改变时触发 选择一页显示多少行
      handleSizeChange(val) {
        this.currentPage = 1;
        this.pageSize = val;
      },
      //当前页改变时触发 跳转其他页
      handleCurrentChange(val) {
        this.currentPage = val;
      },

      //购物车数据库内容动态显示在前端
      cartById() {
        let id = window.sessionStorage.getItem("id")
        console.log(id);
        this.$http.post('http://localhost:8888/queryCartById',
          {id: id},
          {emulateJSON: true})
          .then(res => {
            let carts = res.data.data;
            carts.forEach((item) => {
              if (item.id == id) {
                this.addedGoods.push(item);
              }
            })
          })
      },
      // 计算数量，总额
      handleSum(count, name) {
        let id = window.sessionStorage.getItem("id")
        this.sum = 0;
        this.num = 0;
        this.count1 = count;
        const {data: res} = this.$http.post("http://localhost:8888/updateCart",
          {
            id: id,
            name: name,
            count: this.count1
          }, {emulateJSON: true});


        this.$nextTick(() => {
          // console.log(this.$refs.multipleTable.selection);
          // this.$refs.multipleTable.selection获取被选中的行
          this.$refs.multipleTable.selection.forEach(item => {
            this.sum += (item.price * item.count),
              this.num += (item.count);
          });
        });


      },
      pay(name, price, count) {
        this.$router.push({path: "/ZhiFuBao", query: {price: price, name: name, count: count}})
      },
      payAll(num) {
        alert(num)
        this.$router.push({path: "/ZhiFuBao", query: {num}})
      },


      // 删除购物车操作
      async handleDelete(index, name) {
        let id = window.sessionStorage.getItem("id")
        this.addedGoods.splice(index, 1);
        console.log(index)
        if (confirm('确定要删除吗')) {
          const {data: res} = await this.$http.post("http://localhost:8888/cart/delete",
            {
              id: id,
              name: name
            }, {emulateJSON: true})

          if (res.code === 200) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.handleSum();
            this.reload()
          } else {
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        } else {
          return false
        }
      },
      /*修改购物车操作*/

      //跳转到详情页面
      goodsMsg(index) {
        console.log(index);
        let i=0
        try{
        this.addedGoods.forEach(item => {
          if ( i!= index)
          {
            i++
          }
          else
            {
            this.$router.push({
              path: '/DetailsLayout',
              query: {
                price: item.price,
                brand: item.name,
                goods: item.name,
                img1:item.img,
                /*img1:this.img1,
                img2:this.img2,
                img3:this.$route.query.img3,
                detail1:this.$route.query.detail1,
                detail2:this.$route.query.detail2,
                detail3:this.$route.query.detail3,*/
              }
            });
              throw new Error("ending");


          }


        })}catch (e) {
          if(e.message == "ending"){
            log("结束了") ;
          }else{
            log(e.message);
          }

      }},

      // 添加操作
      handleAdd(i) {
        let flag = false;
        this.addedGoods.forEach(item => {
          if (item.name == this.goods[i].name) {
            item.count++;
            flag = true;
          }
        })
        if (!flag) this.addedGoods.push(this.goods[i]);
      },
    },
    mounted() {
      this.cartById();
    },

  }
</script>

<style scoped>

</style>
